package com.jyniubi.gmail.pms.service.impl;

import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.toolkit.CollectionUtils;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.jyniubi.gmail.pms.entity.AttrEntity;
import com.jyniubi.gmail.pms.entity.SkuEntity;
import com.jyniubi.gmail.pms.mapper.AttrMapper;
import com.jyniubi.gmail.pms.mapper.SkuMapper;
import com.jyniubi.gmail.pms.vo.SaleAttrValueVo;
import org.checkerframework.checker.units.qual.A;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.PageRequest;
import org.springframework.stereotype.Service;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.jyniubi.gmail.common.bean.PageResultVo;
import com.jyniubi.gmail.common.bean.PageParamVo;

import com.jyniubi.gmail.pms.mapper.SkuAttrValueMapper;
import com.jyniubi.gmail.pms.entity.SkuAttrValueEntity;
import com.jyniubi.gmail.pms.service.SkuAttrValueService;
import org.springframework.web.bind.annotation.RequestParam;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;


@Service("skuAttrValueService")
public class SkuAttrValueServiceImpl extends ServiceImpl<SkuAttrValueMapper, SkuAttrValueEntity> implements SkuAttrValueService {

    @Resource
    private AttrMapper attrMapper;
    @Autowired
    private SkuMapper skuMapper;
    @Autowired
    private SkuAttrValueMapper skuAttrValueMapper;
    @Override
    public PageResultVo queryPage(PageParamVo paramVo) {
        IPage<SkuAttrValueEntity> page = this.page(
                paramVo.getPage(),
                new QueryWrapper<SkuAttrValueEntity>()
        );

        return new PageResultVo(page);
    }

    @Override
    public List<SkuAttrValueEntity> querySearchAttrValuesByCidAndSkuId(Long cid, Long skuId) {
        List<AttrEntity> attrEntities = this.attrMapper.selectList(new QueryWrapper<AttrEntity>()
                .eq("category_id", cid)
                .eq("type", 0)
                .eq("search_type", 1));
        if (CollectionUtils.isEmpty(attrEntities)){
            return null;
        }
        List<Long> ids = attrEntities.stream().map(AttrEntity::getId).collect(Collectors.toList());
        List<SkuAttrValueEntity> list = this.list(new QueryWrapper<SkuAttrValueEntity>()
                .eq("sku_id", skuId)
                .in("attr_id", ids));
        return list;
    }

    @Override
    public List<SaleAttrValueVo> querySaleAttrValuesBySpuId(Long spuId) {
        // 1.根据spuid查询sku集合
        List<SkuEntity> skuEntities = this.skuMapper.selectList(new QueryWrapper<SkuEntity>().eq("spu_id",spuId));
        if (CollectionUtils.isEmpty(skuEntities)){
            return null;
        }
        // 获取skuIds集合
        List<Long> skuIds = skuEntities.stream().map(SkuEntity::getId).collect(Collectors.toList());
        // 2.根据skuids集合 查询 spu下所有sku的销售属性
        List<SkuAttrValueEntity> skuAttrValueEntities = this.list(new QueryWrapper<SkuAttrValueEntity>().in("sku_id", skuIds));
        if (CollectionUtils.isEmpty(skuAttrValueEntities)){
            return null;
        }
        // 3.把销售属性entity集合处理成vo集合
        // [{attrId: 3, attrName: 颜色, attrValues: [暗夜黑, 白天白]},
        //  {attrId: 4, attrName: 内存, attrValues: [8G, 12G]},
        //  {attrId: 5, attrName: 存储, attrValues: [128G, 256G]}]
        // 根据attrId对entity集合进行分组  key-attrId value-该组数据集合（entity）
        Map<Long, List<SkuAttrValueEntity>> map = skuAttrValueEntities.stream().collect(Collectors.groupingBy(SkuAttrValueEntity::getAttrId));
        List<SaleAttrValueVo> saleAttrValueVos = new ArrayList<>();
        map.forEach((attrId,attrValueEntities)->{
            SaleAttrValueVo saleAttrValueVo = new SaleAttrValueVo();
            saleAttrValueVo.setAttrId(attrId);
            saleAttrValueVo.setAttrName(attrValueEntities.get(0).getAttrName());
            saleAttrValueVo.setAttrValues(attrValueEntities.stream().map(SkuAttrValueEntity::getAttrValue).collect(Collectors.toSet()));
            saleAttrValueVos.add(saleAttrValueVo);
        });
        return saleAttrValueVos;
    }

    @Override
    public String queryMappingBySpuId(Long spuId) {
        // 1.根据spuid查询sku集合
        List<SkuEntity> skuEntities = this.skuMapper.selectList(new QueryWrapper<SkuEntity>().eq("spu_id", spuId));
        if (CollectionUtils.isEmpty(skuEntities)){
            return null;
        }
        // 获取skuIds集合
        List<Long> skuIds = skuEntities.stream().map(SkuEntity::getId).collect(Collectors.toList());
        //[{sku_id=27, attr_values=白色,8G,512G}, {sku_id=28, attr_values=白色,12G,256G}, {sku_id=29, attr_values=白色,12G,512G}, {sku_id=30, attr_values=白色,8G,256G}]
        // {'暗夜黑,8G,128G': 10, '暗夜黑,12G,256G': 11, '暗夜黑,12G,128G': 12}
        List<Map<String, Object>> maps = this.skuAttrValueMapper.queryMappingBySkuIds(skuIds);
        if(CollectionUtils.isEmpty(maps)){
            return null;
        }
        Map<String, Long> mappingMap = maps.stream().collect(
                Collectors.toMap(map -> map.get("attr_values").toString(),
                        map -> (Long) map.get("sku_id"),
                        (existing, replacement) -> existing, // 如果有重复键，保留现有的值
                        LinkedHashMap::new)); // 使用LinkedHashMap来保持顺序
        return JSON.toJSONString(mappingMap);
    }

}